package com.xaicode.learn.netty.tcpProtocol;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.IntStream;

import static java.nio.charset.StandardCharsets.UTF_8;

/**
 * @author Locker xaicode@sina.com
 * @version 1.0
 * @date 2021/6/20 0020 9:55
 */
@Slf4j
public class NettyClientHandler extends SimpleChannelInboundHandler<MessageProtocol> {

    private final AtomicInteger count = new AtomicInteger(0);

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // send 10 msg
        IntStream.range(1, 11).forEach(i -> {
            String content = String.format("number %d - msg: %s", i, "hello server");
            MessageProtocol messageProtocol = MessageProtocol.builder()
                    .len(content.getBytes(UTF_8).length)
                    .content(content.getBytes(UTF_8))
                    .build();
            ctx.writeAndFlush(messageProtocol);
        });
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MessageProtocol msg) throws Exception {
        // read client msg
        int len = msg.getLen();
        byte[] content = msg.getContent();

        log.info("receive count [{}] msg with length {}: {}", count.incrementAndGet(), len, new String(content, UTF_8));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
